<template>
  <div ref="chartRef" style="height: 300px;"></div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  caloriesInTrend: { type: Array, required: true },
  caloriesOutTrend: { type: Array, required: true }
});

const chartRef = ref(null);
let chartInstance = null;

const renderChart = () => {
  if (!chartRef.value) return;
  if (chartInstance) chartInstance.dispose();
  chartInstance = echarts.init(chartRef.value);
  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['热量摄入', '热量消耗'], top: 'bottom' },
    xAxis: { type: 'category', data: props.caloriesInTrend.map(item => item.date) },
    yAxis: { type: 'value' },
    series: [
      { name: '热量摄入', type: 'bar', stack: 'total', data: props.caloriesInTrend.map(item => item.value), color: '#fc8452' },
      { name: '热量消耗', type: 'bar', stack: 'total', data: props.caloriesOutTrend.map(item => item.value), color: '#9a60b4' }
    ],
    grid: { left: '3%', right: '4%', bottom: '10%', containLabel: true }
  });
};

watch(() => [props.caloriesInTrend, props.caloriesOutTrend], renderChart, { deep: true });
onMounted(() => {
  renderChart();
  window.addEventListener('resize', chartInstance.resize);
});
onUnmounted(() => {
  window.removeEventListener('resize', chartInstance.resize);
  if (chartInstance) chartInstance.dispose();
});
</script>